import cv2
import numpy as np

img = cv2.imread('3/lena_gray.jpg', 0)
x, y = img.shape
# print(x, y)

result = np.zeros((x, y, 8), dtype=np.uint8)
result1 = np.zeros((x, y, 8), dtype=np.uint8)
mask1 = np.ones((x, y), dtype=np.uint8)

cv2.imshow('img', img)

if img is not None:
    for i in range(8):
        # 补全掩码，用于提取第 i 位
        mask1[:, :] = 1 << i

        # 提取图像中第 i 位的位图
        result[:, :, i] = cv2.bitwise_and(img, mask1)

        windowsname = 'result' + str(i)
        cv2.imshow(windowsname, result[:, :, i])

        windowsname1 = 'result_BW' + str(i)
        result1[:, :, i] = result[:, :, i]

        # 非零设置为255，实现黑白图
        result1[:, :, i][result1[:, :, i] > 0] = 255
        cv2.imshow(windowsname1, result1[:, :, i])

    cv2.waitKey()
    cv2.destroyAllWindows()
